package com.ruoyi.web.controller.school;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.school.domain.*;
import com.ruoyi.school.domain.vo.PacAcademicOutputVo;
import com.ruoyi.school.domain.vo.SchoolHonorVo;
import com.ruoyi.school.enums.AuditStatusEnum;
import com.ruoyi.school.service.*;
import com.ruoyi.school.utils.CommonUtils;
import com.ruoyi.system.domain.vo.StuCityVo;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.tool.WordUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/school/student")
public class StudentController extends BaseController {
    @Resource
    StudentService studentService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private AcademicOutputService academicOutputService;

    @Resource
    private PacActualOutputService pacActualOutputService;

    @Resource
    private PacProSkillCertService pacProSkillCertService;

    @Resource
    private PacSoftPatentService pacSoftPatentService;

    @Resource
    private PacScientificProjectsService pacScientificProjectsService;

    @Resource
    private PacJournalsOutputService pacJournalsOutputService;

    @Resource
    private PacLearningFilesDataService pacLearningFilesDataService;


    @Resource
    WordUtil wordUtil;

    @GetMapping("/all")
    public AjaxResult all(Student student) {
        List<Student> students = studentService.getAllByName(student);
        return success(students);
    }

    @PostMapping("/all/nome")
    public AjaxResult allNoMe(@RequestBody Student student) {
        List<Student> students = studentService.getAllByNameNoMe(student);
        return success(students);
    }


    @GetMapping("/list")
    public TableDataInfo list(Student student) {
        startPage();
        List<Student> students = studentService.getList(student);
        return getDataTable(students);
    }


    @GetMapping("/mine")
    public TableDataInfo mine(Student student) {
        List<Student> students = studentService.getMyStuList(student);
        return getDataTable(students);
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response, Student student) {
        List<Student> students = studentService.getMyStuList(student);
        ExcelUtil<Student> util = new ExcelUtil<>(Student.class);
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        util.exportExcel(response, students, user.getNickName() + "的学生");
    }

    /**
     * 毕业生查询
     */
    @GetMapping("/graduated")
    public TableDataInfo graduated(Student student) {
        List<Student> students = studentService.getGraduatedStudent(student);
        return getDataTable(students);
    }

    /**
     * 根据ID 获取学生详情
     */
    @GetMapping("/details")
    public AjaxResult details(Student student) {
        if (student.getId() == null) {
            return error("学生ID不能为空");
        }
        Student student1 = studentService.selectOne(student);
        return success(student1);
    }

    /**
     * 获取所有学生城市数据
     */
    @GetMapping("/city")
    public AjaxResult city() {
        List<StuCityVo> citys = studentService.getAllCity();
        return success(citys);
    }

    /**
     * 获取在校荣誉
     */
    @GetMapping("/school/honor")
    public TableDataInfo schoolHonor(Student student) {
        startPage();
        List<SchoolHonorVo> honors = studentService.getSchoolHonor(student);
        return getDataTable(honors);
    }

    /**
     * 设置是否优秀
     */
    @PutMapping("/setExcellent")
    public AjaxResult setExcellent(@RequestBody Student student) {
        studentService.updateById(student);
        return success();
    }

    /**
     * 获取优秀学生列表
     */
    @GetMapping("/getExcellentList")
    public TableDataInfo getExcellentList(Student student) {
        return getDataTable(studentService.getExcellentList(student));
    }

    /**
     * 导出简历
     */
    @PostMapping("/exportResume")
    public void exportResume(HttpServletResponse response, Student student) {
        // 查询学生详情
        Student details = studentService.selectOne(student);

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=document.docx");

        // 创建文档
        XWPFDocument document = new XWPFDocument();

        // 添加标题
        wordUtil.addTitle(document, details.getStuName() + "简历");

        SysUser sysUser = sysUserService.selectUserById(details.getUserId());

        String sex = Objects.equals(sysUser.getSex(), "0") ? "男" : "女";
        // 4. 添加表格
        List<List<String>> tableData = Arrays.asList(
                Arrays.asList("姓名", details.getStuName(), "性别", sex),
                Arrays.asList("学号", details.getStuNum(), "班级", details.getStuClass()),
                Arrays.asList("院系", details.getStuFaculties(), "联系方式", details.getStuPhone())
        );

//        wordUtil.addTable(document, tableData);

        List<PacAcademicOutput> list1 = academicOutputService.selectStuTop5(student.getId());
        if (!list1.isEmpty()) {
            wordUtil.addEmptyLine(document, 1);
            wordUtil.addParagraph(document, "学科竞赛成果");
            wordUtil.addEmptyLine(document, 1);
        }
        list1.forEach(item -> {
            extracted(item.getAcFileType(), item.getAcFile(), item.getAcTitle(), document);
        });

        List<PacActualOutput> list2 = pacActualOutputService.selectStuTop5(student.getId());
        if (!list2.isEmpty()) {
            wordUtil.addEmptyLine(document, 1);
            wordUtil.addParagraph(document, "实战成果");
            wordUtil.addEmptyLine(document, 1);
        }
        list2.forEach(item -> {
            extracted(item.getAcFileType(), item.getAcFile(), item.getAcTitle(), document);
        });

        List<PacProSkillCert> list3 = pacProSkillCertService.selectStuTop5(student.getId());
        if (!list3.isEmpty()) {
            wordUtil.addEmptyLine(document, 1);
            wordUtil.addParagraph(document, "技能证书");
            wordUtil.addEmptyLine(document, 1);
        }
        list3.forEach(item -> {
            extracted(item.getAcFileType(), item.getAcFile(), item.getAcTitle(), document);
        });

        List<PacSoftPatent> list4 = pacSoftPatentService.selectStuTop5(student.getId());
        if (!list4.isEmpty()) {
            wordUtil.addEmptyLine(document, 1);
            wordUtil.addParagraph(document, "专利/软著");
            wordUtil.addEmptyLine(document, 1);
        }
        list4.forEach(item -> {
            extracted(item.getAcFileType(), item.getAcFile(), item.getAcTitle(), document);
        });

        List<PacScientificProjects> list5 = pacScientificProjectsService.selectStuTop5(student.getId());
        if (!list5.isEmpty()) {
            wordUtil.addEmptyLine(document, 1);
            wordUtil.addParagraph(document, "大创项目");
            wordUtil.addEmptyLine(document, 1);
        }

        list5.forEach(item -> {
            extracted(item.getAcFileType(), item.getAcFile(), item.getAcTitle(), document);
        });

        List<PacJournalsOutput> list6 = pacJournalsOutputService.selectStuTop5(student.getId());
        if (!list6.isEmpty()) {
            wordUtil.addEmptyLine(document, 1);
            wordUtil.addParagraph(document, "论文发表");
            wordUtil.addEmptyLine(document, 1);
        }

        list6.forEach(item -> {
            extracted(item.getAcFileType(), item.getAcFile(), item.getAcTitle(), document);
        });

        // 输出到响应流
        try {
            document.write(response.getOutputStream());
            document.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导出简历
     */
    @PostMapping("/exportResume2")
    public void exportResume(HttpServletResponse response) {
        Student student = CommonUtils.getStudent();
        // 查询学生详情
        Student details = studentService.selectOne(student);

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=document.docx");

        // 创建文档
        XWPFDocument document = new XWPFDocument();

        // 添加标题
        wordUtil.addTitle(document, details.getStuName() + "简历");

        SysUser sysUser = sysUserService.selectUserById(details.getUserId());

        String sex = Objects.equals(sysUser.getSex(), "0") ? "男" : "女";
        // 4. 添加表格
        List<List<String>> tableData = new ArrayList<>(Arrays.asList(
                Arrays.asList("姓名", details.getStuName(), "性别", sex),
                Arrays.asList("学号", details.getStuNum(), "班级", details.getStuClass()),
                Arrays.asList("户籍", details.getStuPlace(), "政治面貌", details.getPoliticalOutlook())
        ));

        // 实战成果
        PacActualOutput pacActualOutput = new PacActualOutput();
        pacActualOutput.setAcAudit(AuditStatusEnum.AUDITED.getCode());
        List<PacActualOutput> list2 = pacActualOutputService.myList(pacActualOutput);
        List<List<Integer>> regionList = new ArrayList<>();

        if (!list2.isEmpty()) {
            List<List<String>> tableData1 = new ArrayList<>();
            list2.forEach(item -> {
                List<String> list = new ArrayList<>();
                list.add("实战成果");
                String time = DateUtils.dateTime(item.getAcTime());
                list.add(time + "获得：" + item.getAcTitle());
                tableData1.add(list);
            });


            List<Integer> integers = new ArrayList<>();

            integers.add(tableData.size());
            integers.add(tableData.size() + tableData1.size());
            integers.add(tableData.size());
            integers.add(tableData1.size());

            tableData.addAll(tableData1);

            regionList.add(integers);
        }


        PacAcademicOutput pacAcademicOutput = new PacAcademicOutput();
        pacAcademicOutput.setAcAudit(AuditStatusEnum.AUDITED.getCode());
        // 学科竞赛成果
        List<PacAcademicOutputVo> list3 = academicOutputService.myList(pacAcademicOutput);
        if (!list3.isEmpty()) {
            List<List<String>> tableData2 = new ArrayList<>();

            list3.forEach(item -> {
                List<String> list = new ArrayList<>();
                list.add("学科竞赛成果");
                String time = DateUtils.dateTime(item.getCreateTime());
                list.add(time + "获得：" + item.getAcTitle());
                tableData2.add(list);
            });

            List<Integer> integers2 = new ArrayList<>();

            integers2.add(tableData.size());
            integers2.add(tableData.size() + tableData2.size());
            integers2.add(tableData.size());
            integers2.add(tableData2.size());

            tableData.addAll(tableData2);

            regionList.add(integers2);
        }

        PacProSkillCert pacProSkillCert = new PacProSkillCert();
        pacProSkillCert.setAcAudit(AuditStatusEnum.AUDITED.getCode());

        // 技能证书
        List<PacProSkillCert> list4 = pacProSkillCertService.myList(pacProSkillCert);

        if (!list4.isEmpty()) {
            List<List<String>> tableData3 = new ArrayList<>();

            list4.forEach(item -> {
                List<String> list = new ArrayList<>();
                list.add("技能证书");
                String time = DateUtils.dateTime(item.getCreateTime());
                list.add(time + "获得：" + item.getAcTitle());
                tableData3.add(list);
            });

            List<Integer> integers = new ArrayList<>();

            integers.add(tableData.size());
            integers.add(tableData.size() + tableData3.size());
            integers.add(tableData.size());
            integers.add(tableData3.size());

            tableData.addAll(tableData3);

            regionList.add(integers);
        }

        // 论文发表
        PacJournalsOutput pacJournalsOutput = new PacJournalsOutput();
        pacJournalsOutput.setAcAudit(AuditStatusEnum.AUDITED.getCode());

        List<PacAcademicOutputVo> list5 = pacJournalsOutputService.myList(pacJournalsOutput);

        if (!list5.isEmpty()) {
            List<List<String>> tableData3 = new ArrayList<>();

            list5.forEach(item -> {
                List<String> list = new ArrayList<>();
                list.add("论文发表");
                String time = DateUtils.dateTime(item.getCreateTime());
                list.add(time + "获得：" + item.getAcTitle());
                tableData3.add(list);
            });

            List<Integer> integers = new ArrayList<>();

            integers.add(tableData.size());
            integers.add(tableData.size() + tableData3.size());
            integers.add(tableData.size());
            integers.add(tableData3.size());

            tableData.addAll(tableData3);

            regionList.add(integers);
        }

        // 大创/科研
        PacScientificProjects pacScientificProjects = new PacScientificProjects();
        pacScientificProjects.setAcAudit(AuditStatusEnum.AUDITED.getCode());

        List<PacScientificProjects> list6 = pacScientificProjectsService.myList(pacScientificProjects);

        if (!list6.isEmpty()) {
            List<List<String>> tableData3 = new ArrayList<>();

            list6.forEach(item -> {
                List<String> list = new ArrayList<>();
                list.add("大创/科研");
                String time = DateUtils.dateTime(item.getAcTime());
                list.add(time + "获得：" + item.getAcTitle());
                tableData3.add(list);
            });

            List<Integer> integers = new ArrayList<>();

            integers.add(tableData.size());
            integers.add(tableData.size() + tableData3.size());
            integers.add(tableData.size());
            integers.add(tableData3.size());

            tableData.addAll(tableData3);

            regionList.add(integers);
        }

        // 专利/软著
        PacSoftPatent pacSoftPatent = new PacSoftPatent();
        pacSoftPatent.setAcAudit(AuditStatusEnum.AUDITED.getCode());

        List<PacSoftPatent> list7 = pacSoftPatentService.myList(pacSoftPatent);

        if (!list7.isEmpty()) {
            List<List<String>> tableData3 = new ArrayList<>();

            list6.forEach(item -> {
                List<String> list = new ArrayList<>();
                list.add("专利/软著");
                String time = DateUtils.dateTime(item.getAcTime());
                list.add(time + "获得：" + item.getAcTitle());
                tableData3.add(list);
            });

            List<Integer> integers = new ArrayList<>();

            integers.add(tableData.size());
            integers.add(tableData.size() + tableData3.size());
            integers.add(tableData.size());
            integers.add(tableData3.size());

            tableData.addAll(tableData3);

            regionList.add(integers);
        }

        // 6211 成绩
        PacLearningFilesData pacLearningFilesData = new PacLearningFilesData();
        pacLearningFilesData.setStuId(student.getId().longValue());
        pacLearningFilesData.setLearningType(1);
        List<PacLearningFilesData> list9 = pacLearningFilesDataService.getList(pacLearningFilesData);
        if (!list9.isEmpty()) {
            List<List<String>> tableData3 = new ArrayList<>();

            list9.forEach(item -> {
                List<String> list = new ArrayList<>();
                list.add("6211成绩");
                Object jsonData = item.getJsonData();
                if (jsonData != null) {
                    String string = jsonData.toString();
                    String replace = string.replace("\"[{\\", "");
                    String replace1 = replace.replace("\\\"", "");
                    String replace2 = replace1.replace("[{", "");
                    String replace3 = replace2.replace("}]", "");
                    list.add(replace3);
                }
                tableData3.add(list);
            });

            List<Integer> integers = new ArrayList<>();

            integers.add(tableData.size());
            integers.add(tableData.size() + tableData3.size());
            integers.add(tableData.size());
            integers.add(tableData3.size());

            tableData.addAll(tableData3);
            regionList.add(integers);
        }


        wordUtil.addTable(document, tableData, regionList);
        // 输出到响应流
        try {
            document.write(response.getOutputStream());
            document.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String formatJson() {

        return "";
    }


    private void extracted(String fileType, String filePath, String title, XWPFDocument document) {
        if (fileType.equals("image")) {
            // 去掉 /profile
            filePath = filePath.replace("/profile", "");
            String imagePath = wordUtil.profilePath + filePath;
            try {
                wordUtil.addImageToDocument(document, imagePath);
                wordUtil.addSmallCenteredText(document, title, 10);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
